package org.demo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author yexi
 */
public class FastjsonUtils {

    /**
     * 获取当前已启用的默认特征
     */
    public static List<String> getDefaultFeature() {
        int defaultFeatures = JSON.DEFAULT_GENERATE_FEATURE;
        return parseFeature(defaultFeatures);
    }

    public static List<String> parseFeature(int features) {
        // 哪种方式都可以
        if (false) {
            String formatString = Integer.toBinaryString(features);
            List<String> collect = IntStream.range(0, formatString.length())
                    .mapToObj(index -> {
                        char c = formatString.charAt(formatString.length() - 1 - index);
                        if (c == '1') {
                            String s = Arrays.stream(SerializerFeature.values())
                                    .filter(f -> f.ordinal() == index)
                                    .findFirst()
                                    .map(f -> f.name())
                                    .get();
                            return s;
                        } else {
                            return null;
                        }
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            return collect;
        } else {
            return Arrays.stream(SerializerFeature.values())
                    .filter(f -> SerializerFeature.isEnabled(features, f))
                    .map(f -> f.name())
                    .collect(Collectors.toList());
        }
    }

}
